import React, { cloneElement, useCallback, useEffect } from 'react'
import {
    bool,
    array,
    string,
    func
} from 'prop-types'

import { TabBarWrapper, TabBarListWrapper } from './styledTabbar'

import { useHistory, useLocation } from 'react-router-dom'

export default function TabBar({
    fixed,
    children,
    selectedIndex,
    setSelectedIndex,
    border,
    route
}) {
    const history = useHistory()
    const location = useLocation()

    useEffect(() => {
        if(route){
            setSelectedIndex(location.pathname.slice(1))
        }
    }, [route,setSelectedIndex,location])

    useEffect(() => {
        if (route) {
            history.listen((route) => {
                setSelectedIndex(route.pathname.slice(1))
            })
        }
    }, [history, setSelectedIndex, route])
    const handleItemClick = useCallback((to, name) => {
        return () => {
            if (route) {
                // 切换路由
                history.push(to)
            } else {
                // 改变tabbar的index, 或者是name, 实现高亮
                setSelectedIndex(name)
            }
        }
    }, [history, route, setSelectedIndex])
    return (
        <TabBarWrapper
        fixed={fixed}
        >
            <TabBarListWrapper
            border={border}
            borderWidth={'1px 0 0 0'}
            >
            {
                React.Children.map(children, (child) => {
                return (
                    // 实现element复制，可以同时将额外的属性传递给克隆返回的element
                    cloneElement(
                    child,
                    {
                        selectedIndex,
                        handleItemClick
                    }
                    )
                )
                })
            }
            </TabBarListWrapper>
        </TabBarWrapper>
    )
}

TabBar.defaultProps = {
    fixed: true,
    route: false
}

  // 定义组件属性（props）的类型
TabBar.propTypes = {
    fixed: bool,
    children: array.isRequired,
    activeColor: string,
    border: bool,
    setSelectedIndex: func,
    route: bool
}